import cgi
from time import strptime,mktime
import sys
sys.path.append('depends')

import simplejson
import twitter
import urllib
import operator
from xml.dom import minidom

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

tweets = {}

class CacheTweet(db.Model):
    id = db.IntegerProperty()
    data = db.TextProperty()

def bitlyAPI(url):
    call = "http://api.bit.ly/expand?version=2.0.1&" + urllib.urlencode({'shortUrl':url}) + "&login=rossimo&apiKey=R_dcfd70eec213afe6948c9a7a16d58efb"
    bit = urllib.urlopen(call)
    ly = bit.read()
    bit.close()
    results = simplejson.loads(ly)
    return str(results['results'][url.split("/")[-1]]['longUrl'])

def tinyurlAPI(url):
    call = "http://api.longurl.org/v1/expand?" + urllib.urlencode({'url':url}) + "&format=json"
    tin = urllib.urlopen(call)
    y = tin.read()
    tin.close()
    results = simplejson.loads(y)
    return str(results["long_url"])

def youtubeAPI(url):
    query = url.split("?")[-1]
    params = dict([param.split('=') for param in query.split('&')])
    print str(params)
    id = params['v']
    
    call = "http://gdata.youtube.com/feeds/api/videos/" + id
    
    title = ""
    
    dom = minidom.parse(urllib.urlopen(call))
    for node in dom.getElementsByTagNameNS('http://www.w3.org/2005/Atom', 'title'):
        title = node.firstChild.data  
    
    return "(" + title + ")"

def mashup(tweet):
    words = tweet.text.split(" ")
    bitly = "http://bit.ly/"
    tinyurl = "http://tinyurl.com/"
    youtube = "youtube.com"

    #Detect Small URLs
    for i in range(len(words)):
        if words[i].lower().find(bitly.lower()) != -1:
            words[i] = bitlyAPI(words[i])
        if words[i].lower().find(tinyurl.lower()) != -1:
            words[i] = tinyurlAPI(words[i])

    #Detect Extra Mashups
    for i in range(len(words)):
        if words[i].lower().find(youtube.lower()) != -1:
            words[i] = youtubeAPI(words[i])   

    newText = ""
    for word in words:
        newText = newText + " " + word
    tweet.SetText(newText.strip())

    return tweet

def addTweets(tweetList):
    global tweets
    for tweet in tweetList:
        if tweet.id not in tweets:
            tweet = mashup(tweet)
            
            # checks to see if ID has been chached
            query = CacheTweet.gql("WHERE id = :1 LIMIT 1", tweet.id)
            
            if not query.count() > 0:
                newCache = CacheTweet()
                newCache.id = tweet.id
                newCache.data = tweet.AsJsonString()
                newCache.put()
            else:
                for cached in query:
                    tweet = twitter.Status.NewFromJsonDict(simplejson.loads(cached.data))
                    tweet.SetText(tweet.text)
            
            tweets[tweet.id] = tweet

class MainPage(webapp.RequestHandler):
    def get(self):
        global tweets
        
        username = cgi.escape(self.request.get('user'))
        password = cgi.escape(self.request.get('pass'))
        
        api = twitter.Api(username,password)
        
        addTweets(api.GetUserTimeline())
        addTweets(api.GetFriendsTimeline())
        addTweets(api.GetMentions())

        sortedTweets = tweets.values()
        sortedTweets.sort()

        
        output = "[\n"
        for tweet in sortedTweets:
            output = output + tweet.AsJsonString() + ",\n"
        output = output[:-2] + "]"
        """
        output = ""
        for tweet in sortedTweets:
            output = output + str(tweet.id) + " - " + str(tweet.in_reply_to_status_id) + "<br/>"   
        """
        tweets = {}
        self.response.out.write(output)
        

class CacheDatabase(webapp.RequestHandler):
    def get(self):
        cachedtweets = CacheTweet.all()
        
        output = ""
        for tweet in cachedtweets:
            output = output + tweet.id + " >> "+ tweet.data + "<br/>"

        self.response.out.write(output)


class ClearDatabase(webapp.RequestHandler):
    def get(self):
        cachedtweets = CacheTweet.all()

        for tweet in cachedtweets:
            tweet.delete()

        self.response.out.write("All cached tweets deleted.")

application = webapp.WSGIApplication(
    [('/', MainPage),('/db',CacheDatabase),('/clear',ClearDatabase)],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()